package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.core.redis.RedisCache;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.DevicePropertiesVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Map;

/**
 * 设备Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-06-08
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IoTDAClient ioTDAClient;

    @Autowired
    private RedisCache redisCache;

    /**
     * 查询设备
     * 
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备列表
     * 
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除设备
     * 
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备信息
     * 
     * @param id 设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    @Override
    public void syncProductList() {
        //1.去iot 平台去查询产品
        ListProductsResponse listProductsResponse = ioTDAClient.listProducts(new ListProductsRequest());
        if(listProductsResponse.getHttpStatusCode()!=200){
           throw new BaseException("物联网接口 - 查询产品，同步失败");
        }
        List<ProductSummary> products = listProductsResponse.getProducts();
        //2.放入到redis
        redisCache.setCacheObject("iot:product_all", JSONUtil.toJsonStr(products));
    }

    @Override
    public List<ProductVo> allProduct() {
        String cacheObject = redisCache.getCacheObject("iot:product_all");
        List<ProductVo> list = JSONUtil.toList(cacheObject, ProductVo.class);
        return list;
    }

    @Override
    public void register(DeviceDto deviceDto) {
        //1.查询设备名称是否重复
        long one =  this.count(new LambdaQueryWrapper<Device>().eq(Device::getDeviceName, deviceDto.getDeviceName()));
        if(one > 0){
           throw new BaseException("该设备"+deviceDto.getDeviceName()+"名称已存在");
        }
        //2.查询设备标识符是否重复
        long two =  this.count(new LambdaQueryWrapper<Device>().eq(Device::getNodeId, deviceDto.getNodeId()));
        if(two > 0){
            throw new BaseException("该设备标识符"+deviceDto.getNodeId()+"已存在");
        }
        //3.查询同一位置是否重复
        long three =  this.count(new LambdaQueryWrapper<Device>()
                .eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                .eq(Device::getLocationType,deviceDto.getLocationType())
                .eq(Device::getPhysicalLocationType,deviceDto.getPhysicalLocationType())
        );
        if(three > 0){
            throw new BaseException("该设备绑定了同一个位置");
        }
        //4.iot 物联网平台注册设备
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();

        body.withDeviceName(deviceDto.getDeviceName());
        body.withNodeId(deviceDto.getNodeId());
        body.withProductId(deviceDto.getProductKey());

        request.withBody(body);
        AddDeviceResponse addDeviceResponse = ioTDAClient.addDevice(request);
        if(addDeviceResponse.getHttpStatusCode()!=201){
           throw new BaseException("新增设备失败");
        }


        //5.数据插入数据
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        device.setIotId(addDeviceResponse.getDeviceId());
        device.setSecret(addDeviceResponse.getAuthInfo().getSecret());
        
        this.save(device);
    }

    @Override
    public DeviceDetailVo queryDevice(String iotId) {
        //查询iot 物联网
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.withDeviceId(iotId);
        ShowDeviceResponse showDeviceResponse = ioTDAClient.showDevice(request);
        if (showDeviceResponse.getHttpStatusCode()!=200){
            throw new BaseException("IOT 物联网平台没有该设备");
        }
        //查询数据库
        Device device = this.getOne(new LambdaQueryWrapper<Device>().eq(Device::getIotId, iotId));

        DeviceDetailVo deviceDetailVo = BeanUtil.toBean(device, DeviceDetailVo.class);
        deviceDetailVo.setDeviceStatus(showDeviceResponse.getStatus());
        LocalDateTime activeTime = LocalDateTimeUtil.parse(showDeviceResponse.getActiveTime(), DatePattern.UTC_MS_PATTERN);
        //日期时区转换
        activeTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();
        deviceDetailVo.setActiveTime(activeTime);

        //3.组合数据
        return deviceDetailVo;
    }


    @Override
    public void updateIotDevice(DeviceDto deviceDto) {
       //1.修改iot 平台
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.withDeviceId(deviceDto.getIotId());
        UpdateDevice body = new UpdateDevice();
        body.withDeviceName(deviceDto.getDeviceName());
        request.withBody(body);
        UpdateDeviceResponse updateDeviceResponse = ioTDAClient.updateDevice(request);
        if(updateDeviceResponse.getHttpStatusCode()!=200){
           throw new BaseException("设备不能修改");
        }
        //2.修改数据库
        Device device = BeanUtil.toBean(deviceDto, Device.class);

        this.updateById(device);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteIotDevice(String iotId) {
        //1.删iot
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.withDeviceId(iotId);
        DeleteDeviceResponse deleteDeviceResponse = ioTDAClient.deleteDevice(request);
        if(deleteDeviceResponse.getHttpStatusCode()!=204){
            throw new BaseException("不能删除设备");
        }
        //2.删数据库
        this.remove(new LambdaQueryWrapper<Device>().eq(Device::getIotId,iotId));
    }

    @Override
    public List<DevicePropertiesVo> queryServiceProperties(String iotId) {
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(iotId);
        ShowDeviceShadowResponse showDeviceShadowResponse = ioTDAClient.showDeviceShadow(request);
        if (showDeviceShadowResponse.getHttpStatusCode()!=200){
          throw new BaseException("查询不到设备的上报信息");
        }
        List<DeviceShadowData> shadowList = showDeviceShadowResponse.getShadow();
        List<DevicePropertiesVo> propertiesVoList = new ArrayList<>();


        LocalDateTime activeTime = LocalDateTimeUtil.parse(shadowList.get(0).getReported().getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
        //日期时区转换
        activeTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();

        JSONObject properties = JSONUtil.parseObj(shadowList.get(0).getReported().getProperties());
        for (Map.Entry<String, Object> property : properties) {
            DevicePropertiesVo devicePropertiesVo = new DevicePropertiesVo();
            devicePropertiesVo.setFunctionId(property.getKey());
            devicePropertiesVo.setValue(property.getValue());

            devicePropertiesVo.setEventTime(activeTime);
            propertiesVoList.add(devicePropertiesVo);
        }

        return propertiesVoList;
    }

    @Override
    public List<ServiceCapability> queryProduct(String productKey) {
        ShowProductRequest request = new ShowProductRequest();
        request.withProductId(productKey);
        ShowProductResponse showProductResponse = ioTDAClient.showProduct(request);
        if (showProductResponse.getHttpStatusCode()!=200){
            throw new BaseException("没用该产品信息");
        }
        List<ServiceCapability> serviceCapabilities = showProductResponse.getServiceCapabilities();
        return serviceCapabilities;

    }
}
